package com.gxpt.app.view;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.createtime_Adapter;
import com.gxpt.app.bean.createtime_my_bean;
import com.gxpt.app.bean.normal;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_createtime_main)
public class Activity_createtime_main extends BaseActivity {

    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private createtime_Adapter mDataAdapter = null;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;

    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.txt_right)
    TextView txt_right;

    @ViewInject(R.id.toAdd)
    Button toAdd;

    @ViewInject(R.id.txt_price_shengyu)
    TextView txt_price_shengyu;

    @ViewInject(R.id.txt_price_sum)
    TextView txt_price_sum;


    double price_sum     = 0.0;
    double price_lose    = 0.0;//剩余金额

    String s="";

    //
    String demand_id,bid_id,stage_content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);

        Bundle b = getIntent().getBundleExtra("DATA");
        if(b != null){
            demand_id  = b.getString("demand_id");
            bid_id     = b.getString("bid_id");
            price_sum  = b.getDouble("project_amount");
            price_lose = price_sum;
//            Logger.i("demand_id= "+demand_id +"  bid_id= "+bid_id+ "  price_sum="+price_sum);
        }
        initView();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        if(messageEvent.getMessageType()==Constant.ACTION_to_gq){
            s = messageEvent.getMessage();

            stage_content = messageEvent.getId1();
            Logger.i("tmp_json = "+stage_content);

//            double t = price_sum- Double.parseDouble(messageEvent.getId2());

            double t = AppUtils.double_sub(price_sum,Double.parseDouble(messageEvent.getId2()));

            txt_price_shengyu.setText(getValue(""+t));
            price_lose = t;
            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
            mCurrentCounter = 0;
            do_Refresh();
        }
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_tianjiaxiangmugongqi));
        txt_right.setVisibility(View.VISIBLE);
        txt_price_sum.setText(getValue(""+price_sum));
        txt_price_shengyu.setText(getValue(""+price_sum));

        mDataAdapter = new createtime_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
//        mLRecyclerViewAdapter.addHeaderView(topView);

        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(false);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    createtime_my_bean.stage item = mDataAdapter.getDataList().get(position);

                    Bundle b = new Bundle();
                    b.putDouble("P_SUM"  ,price_sum);
                    b.putInt("index_list",position);
                    b.putDouble("P_LOSE" ,price_lose);
                    b.putBoolean("IS_ADD" ,false);

                    b.putString("T_B" ,item.t_b);
                    b.putString("T_E" ,item.t_e);
                    b.putDouble("current_price" ,item.price);

                    b.putString("Current_json",s);
                    jumpActivity(Activity_createtime_sub.class,b,false);

                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private String getValue(String de){
        return ""+de+"元";
    }

    @Override
    public void initData() {

    }

    private void do_Refresh(){
        page_num = 1;
        setList();//最新
    }

    private void do_LoadMore(){
//        page_num += 1;
//        setList();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<createtime_my_bean.stage> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }

    @Event(value={R.id.toback,R.id.txt_right,R.id.toAdd})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toback:
                closeActivity();
                break;
            case R.id.txt_right:
                if(checkViews()){
                    toNet_createtime();
                }
                break;
            case R.id.toAdd:
                Bundle b = new Bundle();
                b.putDouble("P_SUM"  ,price_sum);
                b.putDouble("P_LOSE" ,price_lose);
                b.putBoolean("IS_ADD" ,true);
                b.putString("Current_json",s);
                jumpActivity(Activity_createtime_sub.class,b,false);
                break;
        }
    }

    private boolean checkViews(){
        if(price_lose !=0){
            Toast.makeText(context,""+getResources().getString(R.string.alert_putisnotnull_work),Toast.LENGTH_LONG).show();
            return false;
        }else{
            return true;
        }

    }

    private void setList(){
        mLRecyclerView.refreshComplete(REQUEST_COUNT);
        try{
            createtime_my_bean data = new Gson().fromJson(s, createtime_my_bean.class);
                if(data.data != null){
                    if(data.data.size()>0){
                        addItems((ArrayList)data.data);
                        notifyDataSetChanged();
                    }else{
                        page_num -= 1;
                    }
                }
        }catch (Exception e){
            e.printStackTrace();
        }
    }




    //////NET DO
    StringCallback do_createtime = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e("添加工期 B= "+s);
            try{
                normal data = new Gson().fromJson(s, normal.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_to_gq_submit));
                    closeActivity();
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    /////NET
    private void toNet_createtime(){
        hud.show();




        JSONObject jsonBody=new JSONObject();
        try {


            JSONObject obj = new JSONObject(stage_content);


            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "demand");
            jsonBody.put("serviceName",          "createtime");

            jsonBody.put("demand_id",          demand_id);
            jsonBody.put("member_id",          AppUtils.get_user_id(context));
            jsonBody.put("bid_id",             bid_id);
            jsonBody.put("project_amount",     price_sum);
            jsonBody.put("stage_content",      obj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i("toNet_createtime = "+jsonBody.toString()+"  ["+Constant.URL_createtime+"]");
        HttpUtils.http_post_string(Constant.URL_createtime,jsonBody.toString(),do_createtime);
    }
}
